package parser

import (
	"encoding/json"
	"fmt"
	"log"
	"my-crawler/concurrence/engine"
	"my-crawler/concurrence/fetcher"
	"my-crawler/concurrence/task"
	"strconv"
	"time"
)

type Result struct {
	AppMsgList []Detail `json:"app_msg_list"`
}

type Detail struct {
	UpdateTime int64 `json:"update_time"`
	Title      string
	Link       string
	Itemidx    int
}

//一般用于接口返回json格式的解析
func ApiJsonParser(content []byte, ReqData engine.ReqData) engine.ParserResult {
	fmt.Println(string(content))
	time.Sleep(2 * time.Second)
	//解析json
	var result Result
	err := json.Unmarshal(content, &result)
	if len(result.AppMsgList) == 0 {
		//返回err了 结束进程
		log.Fatal(err)
	}
	res := engine.ParserResult{}
	for _, detail := range result.AppMsgList {
		//保存数据库
		res.Item = append(res.Item, detail)
	}

	//更改翻页
	var cursor int
	if begin, ok := ReqData.Payload["begin"]; ok {
		fmt.Printf("begin : %s", begin)

		cursor, _ = strconv.Atoi(begin)
		if cursor == task.End {
			return engine.NilParserResult()
		}
		cursor += 5
		ReqData.Payload["begin"] = fmt.Sprintf("%d", cursor)
	}
	fmt.Println("=====请求参数=====")
	fmt.Println(ReqData.Payload)
	//追加请求
	res.Request = append(res.Request, engine.CrawlerRequest{
		ReqData:  ReqData,           //数据初始化
		HttpFunc: &fetcher.GetReq{}, //请求
		Parser:   ApiJsonParser,
	})
	return res
}
